package com.pine.dbant.plugin.mysql.function;

import com.pine.dbant.common.jdbc.JdbcUtils;
import com.pine.dbant.common.model.Table;
import com.pine.dbant.common.plugin.meta.JdbcMetaAnalysisException;
import com.pine.dbant.common.plugin.meta.JdbcMetadataAnalysisConfig;
import com.pine.dbant.common.plugin.meta.QueryMetadataParam;
import com.pine.dbant.common.plugin.meta.function.jdbc.TableDetailFunction;
import com.pine.sunflower.core.utils.Strings;

import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Map;

/**
 * @author xiaoyuan
 * @create 2023/1/4 14:15
 **/
public class MysqlQueryTableDetailFunction  extends TableDetailFunction {


    @Override
    public Table query(JdbcMetadataAnalysisConfig metadataAnalysisConfig, QueryMetadataParam queryMetadataParam) {
        String catalog = queryMetadataParam.getConfiguration().getNecessaryValue("catalog");
        String tableName = queryMetadataParam.getConfiguration().getNecessaryValue("tableName");
        String sql = Strings.format(" select  t1.* , t2.CHARACTER_SET_NAME  from information_schema.tables t1 " +
                "left join   information_schema.COLLATION_CHARACTER_SET_APPLICABILITY  t2  on t1.table_collation = t2.collation_name " +
                "where   t1.table_schema='{}'  AND t1.TABLE_NAME='{}'  ", catalog,tableName);
        Map<String, Object> result = JdbcUtils.getSqlRunner(metadataAnalysisConfig.getConnection()).selectOne(sql);
        if(result==null){
            throw new JdbcMetaAnalysisException(Strings.format("未发现表信息[{}]",tableName));
        }
        Object tableCatalog =  result.get("TABLE_CATALOG");
        Object tableSchema =  result.get("TABLE_SCHEMA");
       // Object tableName =  result.get("TABLE_NAME");
        Object tableType =  result.get("TABLE_TYPE");
        Object tableComment =  result.get("TABLE_COMMENT");
        Table table = new Table();
        table.setKey(tableName);
        table.setTableName(tableName);
        table.setTableType(String.valueOf(tableType));
        if(tableCatalog!=null){
            table.setCatalogName(catalog);
        }
        if(tableComment!=null){
            table.setTableComment(String.valueOf(tableComment));
        }
        table.setProperties(result);
        DatabaseMetaData dbMetaData;
        try {
            dbMetaData = metadataAnalysisConfig.getConnection().getMetaData();
        } catch (SQLException e) {
            throw new JdbcMetaAnalysisException(e.getMessage(), e);
        }
        table.setFields(buildFiled(dbMetaData,catalog,null,tableName));
        return table;
    }
}
